/*
 * Copyright (C) 2009 AnK Team
 *	 Andrey Korolev
 *	 Anna Krel
 *	 Anna Kapanina
 *	 
 *	 http://code.google.com/p/ankfood/	
 *    
     
 *    Licensed under the GNU General Public License, Version 2.0 (the "License");
 *
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *         http://www.gnu.org/licenses/gpl-2.0.html

 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,

 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

package org.ank.food;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class ProductListActivity extends Activity {
    
	private final static int RESULT_FROM_PRODUCT_INFO = 1;
	protected final static int MAX_TITLE_LENGTH = 15;
	protected final static int SHOW_ALL_MODE = 0;
	protected final static int SHOW_GROUPS_MODE = 1;
	protected final static int SHOW_SUBGROUPS_FROM_GROUP_MODE = 2;
	protected final static int SHOW_PRODUCTS_FROM_SUBGROUP_MODE = 3;
	protected final static int SHOW_GROUPS_FOR_ADVICE_MODE = 4;
	protected final static int SHOW_PRODUCTS_FROM_GROUP_MODE = 5;
	protected final static int SHOW_PRODUCTS_FROM_SEARCH_RESULT = 6;
	public final static String INTENT_EXTRA_NAME_MODE = "conf_exp_extra";
	public final static String INTENT_EXTRA_NAME_SUBGROUP = "subgroup_extra";
	
	public final static String PREFS_MODE = "prod list mode";
	public final static String PREFS_CUR_POS = "prod list pos";
	public final static String PREFS_CURRENT_GROUP_ID = "conf exp current group id";
	public final static String PREFS_CURRENT_GROUP_POS = "conf exp current group pos";
	public final static String PREFS_CURRENT_SUBGROUP_ID = "conf exp current subgroup id";
	public final static String PREFS_CURRENT_SUBGROUP_POS = "conf exp current subgroup pos";

	private ListView listView;
	private SimpleCursorAdapter adapter;
	private Button backButton, searchButton;
	private int mode;
	protected int selectedProductId;
	private StringBuffer buf;
	private EditText searchField;
	private TextView title;
	
	
	
	
	@Override
	public void onCreate(Bundle b){
		super.onCreate(b);
		setContentView(R.layout.product_list_activity);
		backButton = (Button)findViewById(R.id.product_list_back_button);
		listView = (ListView)findViewById(R.id.product_list_list);
		searchField = (EditText)findViewById(R.id.product_list_search_field);
		searchButton = (Button)findViewById(R.id.product_list_search_button);
		title = (TextView)findViewById(R.id.product_list_title);
		Intent parentIntent = getIntent();
//		if (parentIntent.hasExtra(INTENT_EXTRA_NAME_SUBGROUP)){
//			mode = SHOW_PRODUCTS_FROM_SUBGROUP_MODE;
//			int subGroupId = parentIntent.getIntExtra(INTENT_EXTRA_NAME_SUBGROUP, 0);
////			//Log.v("ConfExp","sbgrp "+subGroupId);
//			SharedPreferences.Editor editor = getPreferences(0).edit();
//			editor.putInt(PREFS_CURRENT_SUBGROUP_ID, subGroupId);
//			editor.commit();
//			setMode(mode/*, subGroupId, 0*/);
//		}else{
			SharedPreferences.Editor editor = getPreferences(0).edit();
			editor.remove(PREFS_CURRENT_GROUP_ID);
			editor.remove(PREFS_CURRENT_GROUP_POS);
			editor.remove(PREFS_CURRENT_SUBGROUP_ID);
			editor.remove(PREFS_CURRENT_SUBGROUP_POS);
			editor.commit();
			setMode( parentIntent.getIntExtra(INTENT_EXTRA_NAME_MODE, SHOW_GROUPS_MODE) );
//		}
	}
	
	private void setMode(int newMode){

		mode = newMode;
		final SharedPreferences.Editor editor = getPreferences(0).edit();
		editor.putInt(PREFS_MODE, mode);
		editor.commit();
		
		switch(newMode){
			case SHOW_GROUPS_MODE:
				title.setText(R.string.groups);
				backButton.setVisibility(View.GONE);
				searchButton.setOnClickListener(new Button.OnClickListener(){
					public void onClick(View v) {
						setMode(SHOW_PRODUCTS_FROM_SEARCH_RESULT);
					}
				});
				adapter = new SimpleCursorAdapter(getApplicationContext(),
						R.layout.product_list_item, 
						ProductDataManager.getInstance(getApplicationContext()).getGroupsNames(),
						new String[]{
								ProductDataProvider.COLUMN_NAMES_GROUPS[ProductDataProvider.GROUP_NAME]
						},
						new int[]{R.id.product_list_item_text});
				adapter.setFilterQueryProvider(new FilterQueryProvider(){
					public Cursor runQuery(CharSequence constraint) {
						return getApplicationContext().getContentResolver().query(
								ProductDataProvider.CONTENT_URI_GROUPS,
								new String[]{ProductDataProvider.COLUMN_NAMES_GROUPS[ProductDataProvider.ID],
										ProductDataProvider.COLUMN_NAMES_GROUPS[ProductDataProvider.GROUP_NAME]},
										ProductDataProvider.COLUMN_NAMES_GROUPS[ProductDataProvider.GROUP_NAME]+
										" LIKE \"%" +constraint+"%\"", null,
										ProductDataProvider.COLUMN_NAMES_GROUPS[ProductDataProvider.GROUP_NAME]);
					}
				});
				listView.setAdapter(adapter);
				listView.setSelection(getPreferences(0).getInt(PREFS_CURRENT_GROUP_POS, 0));
				listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
					public void onItemClick(AdapterView parent, View view, int pos,
							long row) {
						SharedPreferences.Editor editor = getPreferences(0).edit();
						editor.putInt(PREFS_CURRENT_GROUP_POS, pos);
						editor.putInt(PREFS_CURRENT_GROUP_ID, (int)row);
						editor.commit();	
						setMode(SHOW_SUBGROUPS_FROM_GROUP_MODE);
					}
				});
				break;
		
//		case SHOW_GROUPS_FOR_ADVICE_MODE:
////			//Log.v("conf_exp","in SHOW_GROUPS_FOR_ADVICE_MODE");
////			setContentView(R.layout.confirm_experience_activity_advice_mode);
//			listView = (ListView)findViewById(R.id.confirm_experience_list_advice_mode);
//			adapter = new SimpleCursorAdapter(getApplicationContext(),
//					android.R.layout.simple_list_item_1, 
//					ProductDataManager.getInstance(getApplicationContext()).getGroupsNames(),
//					new String[]{
//						ProductDataProvider.COLUMN_NAMES_GROUPS[ProductDataProvider.GROUP_NAME]
//					},
//					new int[]{android.R.id.text1});
//			adapter.setFilterQueryProvider(new FilterQueryProvider(){
//				@Override
//				public Cursor runQuery(CharSequence constraint) {
//					return getApplicationContext().getContentResolver().query(
//							ProductDataProvider.CONTENT_URI_GROUPS,
//							new String[]{ProductDataProvider.COLUMN_NAMES_GROUPS[ProductDataProvider.ID],
//								ProductDataProvider.COLUMN_NAMES_GROUPS[ProductDataProvider.GROUP_NAME]},
//							ProductDataProvider.COLUMN_NAMES_GROUPS[ProductDataProvider.GROUP_NAME]+
//							" LIKE \"%" +constraint+"%\"", null,
//							ProductDataProvider.COLUMN_NAMES_GROUPS[ProductDataProvider.GROUP_NAME]);
//					}
//				});
//			listView.setAdapter(adapter);
//			listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
//				@Override
//				public void onItemClick(AdapterView parent, View view, int pos,
//						long row) {
//					Intent intent = new Intent();
//        			intent.setClass(getApplicationContext(), EatenTodayActivity.class);
//        			intent.putExtra(EatenTodayActivity.INTENT_EXTRA_NAME,
//            				(int)row);
//        			startActivity(intent);
//        			finish();
//				}
//			});
//			break;	
			
		case SHOW_SUBGROUPS_FROM_GROUP_MODE:
			buf = new StringBuffer();
			buf.append(	ProductDataManager.getInstance(getApplicationContext()).
					getGroupNameById(
							getPreferences(0).getInt(PREFS_CURRENT_GROUP_ID, 0)
							)
					);
			if(buf.length() > MAX_TITLE_LENGTH){
				buf.delete(MAX_TITLE_LENGTH-4, buf.length());
				buf.append("...");
			}
			title.setText(buf.toString());
			buf.delete(0, buf.length());
			
			backButton.setVisibility(View.VISIBLE);
			
//			buf = new StringBuffer(getString(R.string.back_to));
			buf.append(' ').append(getString(R.string.groups));
			backButton.setText(buf.toString());
			backButton.setOnClickListener(new Button.OnClickListener(){
				public void onClick(View v) {
					setMode(SHOW_GROUPS_MODE);
				}
			});
			searchButton.setOnClickListener(new Button.OnClickListener(){
				public void onClick(View v) {
					setMode(SHOW_PRODUCTS_FROM_SEARCH_RESULT);
				}
			});
			final int groupId = getPreferences(0).getInt(PREFS_CURRENT_GROUP_ID, 0);
			Cursor c = ProductDataManager.getInstance(getApplicationContext()).
				getSubgroupsNames(groupId);
			c.moveToFirst();
			if(c.getCount() == 0){
				c.close();
				setMode(SHOW_PRODUCTS_FROM_GROUP_MODE);
				break;
			}
			adapter = new SimpleCursorAdapter(getApplicationContext(),
					R.layout.product_list_item, 
					c,
					new String[]{
						ProductDataProvider.COLUMN_NAMES_SUBGROUPS[ProductDataProvider.
						                                           SUBGROUP_NAME_SUBGROUPS]
					},
					new int[]{R.id.product_list_item_text});
//			adapter.setFilterQueryProvider(new FilterQueryProvider(){
//				public Cursor runQuery(CharSequence constraint) {
//					return getApplicationContext().getContentResolver().query(
//							ProductDataProvider.CONTENT_URI_SUBGROUPS,
//							new String[]{ProductDataProvider.COLUMN_NAMES_SUBGROUPS[ProductDataProvider.ID],
//								ProductDataProvider.COLUMN_NAMES_SUBGROUPS[ProductDataProvider.
//								                                           SUBGROUP_NAME_SUBGROUPS]},
//							ProductDataProvider.COLUMN_NAMES_SUBGROUPS[ProductDataProvider.
//							                                          SUBGROUP_NAME_SUBGROUPS]+
//							" LIKE \"%" +constraint+"%\" AND "+
//							ProductDataProvider.COLUMN_NAMES_SUBGROUPS[ProductDataProvider.GROUP_ID_SUBGROUPS]+
//							" = "+String.valueOf(groupId)
//							, null, 
//							ProductDataProvider.COLUMN_NAMES_SUBGROUPS[ProductDataProvider.
//							                                           SUBGROUP_NAME_SUBGROUPS]);
//					}
//				});
			listView.setAdapter(adapter);
			listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
				public void onItemClick(AdapterView parent, View view, int pos,
						long row) {
					editor.putInt(PREFS_CURRENT_SUBGROUP_POS, pos);
					editor.putInt(PREFS_CURRENT_SUBGROUP_ID, (int)row);
					editor.commit();
					setMode(SHOW_PRODUCTS_FROM_SUBGROUP_MODE);
				}
			});
			listView.setSelection(getPreferences(0).getInt(PREFS_CURRENT_SUBGROUP_POS, 0));
			break;
			
		case SHOW_PRODUCTS_FROM_GROUP_MODE:
			buf = new StringBuffer();
			buf.append(	ProductDataManager.getInstance(getApplicationContext()).
					getGroupNameById(
							getPreferences(0).getInt(PREFS_CURRENT_GROUP_ID, 0)
							)
					);
			if(buf.length() > MAX_TITLE_LENGTH){
				buf.delete(MAX_TITLE_LENGTH-4, buf.length());
				buf.append("...");
			}
			title.setText(buf.toString());
			buf.delete(0, buf.length());
			backButton.setVisibility(View.VISIBLE);
//			buf = new StringBuffer(getString(R.string.back_to));
			
			buf.append(' ').append(getString(R.string.groups));
			
			if(buf.length() > MAX_TITLE_LENGTH){
				buf.delete(MAX_TITLE_LENGTH-4, buf.length());
				buf.append("...");
			}
			backButton.setText(buf.toString());
			backButton.setOnClickListener(new Button.OnClickListener(){
				public void onClick(View arg0) {
					setMode(SHOW_GROUPS_MODE);
				}
			});
			searchButton.setOnClickListener(new Button.OnClickListener(){
				public void onClick(View v) {
					setMode(SHOW_PRODUCTS_FROM_SEARCH_RESULT);
				}
			});
			adapter = new SimpleCursorAdapter(getApplicationContext(),
					R.layout.product_list_item, 
					ProductDataManager.getInstance(getApplicationContext()).
							getProductsByGroup(getPreferences(0).getInt(PREFS_CURRENT_GROUP_ID, 0)),
					new String[]{
						ProductDataProvider.COLUMN_NAMES_PRODUCTS[ProductDataProvider.NAME]
					},
					new int[]{R.id.product_list_item_text});
//			adapter.setFilterQueryProvider(new FilterQueryProvider(){
//				public Cursor runQuery(CharSequence constraint) {
//					return ProductDataManager.getInstance(getApplicationContext()).
//							getProductsByGroupFiltered(
//									getPreferences(0).getInt(PREFS_CURRENT_GROUP_ID, 0), 
//									constraint.toString()
//							);
//					}
//				});
			listView.setAdapter(adapter);
			listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
				public void onItemClick(AdapterView parent, View view, int pos,
						long row) {
					
					selectedProductId = (int) row;
					
					editor.remove(PREFS_CURRENT_GROUP_ID);
					editor.remove(PREFS_CURRENT_GROUP_POS);
					editor.remove(PREFS_CURRENT_SUBGROUP_ID);
					editor.remove(PREFS_CURRENT_SUBGROUP_POS);
					editor.commit();
					
					Intent intent = new Intent();
	        		intent.setClass(getApplicationContext(), ProductInfoActivity.class);
	        		intent.putExtra(ProductInfoActivity.INTENT_EXTRA_NAME_PROD_ID, selectedProductId);
	        		startActivityForResult(intent,RESULT_FROM_PRODUCT_INFO);
				}
			});
			break;
		case SHOW_PRODUCTS_FROM_SUBGROUP_MODE:
			buf = new StringBuffer();
			buf.append(	ProductDataManager.getInstance(getApplicationContext()).
					getSubgroupNameById(
							getPreferences(0).getInt(PREFS_CURRENT_SUBGROUP_ID, 0)
							)
					);
			if(buf.length() > MAX_TITLE_LENGTH){
				buf.delete(MAX_TITLE_LENGTH-4, buf.length());
				buf.append("...");
			}
			title.setText(buf.toString());
			buf.delete(0, buf.length());
			backButton.setVisibility(View.VISIBLE);
//			buf = new StringBuffer(getString(R.string.back_to));
			
			buf.append(' ').
			append(ProductDataManager.getInstance(getApplicationContext()).
					getGroupNameById(
							getPreferences(0).getInt(PREFS_CURRENT_GROUP_ID, 0)
							)
					);
			
			if(buf.length() > MAX_TITLE_LENGTH){
				buf.delete(MAX_TITLE_LENGTH-4, buf.length());
				buf.append("...");
			}
			backButton.setText(buf.toString());
			backButton.setOnClickListener(new Button.OnClickListener(){
				public void onClick(View v) {
					setMode(SHOW_SUBGROUPS_FROM_GROUP_MODE);
				}
			});
			searchButton.setOnClickListener(new Button.OnClickListener(){
				public void onClick(View v) {
					setMode(SHOW_PRODUCTS_FROM_SEARCH_RESULT);
				}
			});
			adapter = new SimpleCursorAdapter(getApplicationContext(),
					R.layout.product_list_item, 
					ProductDataManager.getInstance(getApplicationContext()).
							getProductsBySubgroup(getPreferences(0).getInt(PREFS_CURRENT_SUBGROUP_ID, 0)),
					new String[]{
						ProductDataProvider.COLUMN_NAMES_PRODUCTS[ProductDataProvider.NAME]
					},
					new int[]{R.id.product_list_item_text});
//			adapter.setFilterQueryProvider(new FilterQueryProvider(){
//				public Cursor runQuery(CharSequence constraint) {
//					return ProductDataManager.getInstance(getApplicationContext()).
//							getProductsBySubgroupFiltered(
//									getPreferences(0).getInt(PREFS_CURRENT_SUBGROUP_ID, 0), 
//									constraint.toString()
//							);
//					}
//				});
			listView.setAdapter(adapter);
			listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
				public void onItemClick(AdapterView parent, View view, int pos,
						long row) {
					selectedProductId = (int) row;
					Intent intent = new Intent(getApplicationContext(), ProductInfoActivity.class);
	        		intent.putExtra(ProductInfoActivity.INTENT_EXTRA_NAME_PROD_ID, selectedProductId);
	        		startActivityForResult(intent,RESULT_FROM_PRODUCT_INFO);
				}
			});
			break;
		case SHOW_PRODUCTS_FROM_SEARCH_RESULT:
			editor.remove(PREFS_CURRENT_GROUP_ID);
			editor.remove(PREFS_CURRENT_GROUP_POS);
			editor.remove(PREFS_CURRENT_SUBGROUP_ID);
			editor.remove(PREFS_CURRENT_SUBGROUP_POS);
			editor.commit();
			buf = new StringBuffer(searchField.getText().toString());
			if(buf.length() > MAX_TITLE_LENGTH){
				buf.delete(MAX_TITLE_LENGTH-4, buf.length());
				buf.append("...");
			}
			buf.insert(0,'\n').insert(0,getString(R.string.search_));
			title.setText(buf.toString());
			backButton.setVisibility(View.VISIBLE);
			
			buf.delete(0, buf.length());
			buf.append(getString(R.string.groups));
			
			if(buf.length() > MAX_TITLE_LENGTH){
				buf.delete(MAX_TITLE_LENGTH-4, buf.length());
				buf.append("...");
			}
			backButton.setText(buf.toString());
			backButton.setOnClickListener(new Button.OnClickListener(){
				public void onClick(View arg0) {
					setMode(SHOW_GROUPS_MODE);
				}
			});
			searchButton.setOnClickListener(new Button.OnClickListener(){
				public void onClick(View v) {
					setMode(SHOW_PRODUCTS_FROM_SEARCH_RESULT);
				}
			});
			
			adapter = new SimpleCursorAdapter(getApplicationContext(),
					R.layout.product_list_item, 
					ProductDataManager.getInstance(getApplicationContext()).
							getProductsSearchResult( searchField.getText().toString() ),
					new String[]{
						ProductDataProvider.COLUMN_NAMES_PRODUCTS[ProductDataProvider.NAME]
					},
					new int[]{R.id.product_list_item_text});
//			adapter.setFilterQueryProvider(new FilterQueryProvider(){
//				public Cursor runQuery(CharSequence constraint) {
//					return ProductDataManager.getInstance(getApplicationContext()).
//							getProductsByGroupFiltered(
//									getPreferences(0).getInt(PREFS_CURRENT_GROUP_ID, 0), 
//									constraint.toString()
//							);
//					}
//				});
			listView.setAdapter(adapter);
			listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
				public void onItemClick(AdapterView parent, View view, int pos,
						long row) {
					
					selectedProductId = (int) row;
					
					
					
					Intent intent = new Intent();
	        		intent.setClass(getApplicationContext(), ProductInfoActivity.class);
	        		intent.putExtra(ProductInfoActivity.INTENT_EXTRA_NAME_PROD_ID, selectedProductId);
	        		startActivityForResult(intent,RESULT_FROM_PRODUCT_INFO);
				}
			});
			break;
			
			
		}
	}
	
	protected void onActivityResult(int requestCode, int resultCode,
            Intent data) {
        if (requestCode == RESULT_FROM_PRODUCT_INFO) {
            if (resultCode == RESULT_OK) {
            	Intent intent = new Intent(getApplicationContext(), MenuActivity.class);
				startActivity(intent);
				finish();
            }
        }
    }
//	
//	@Override
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//		if (keyCode == KeyEvent.KEYCODE_BACK) {
//			switch(mode){
//			case SHOW_GROUPS_FOR_ADVICE_MODE:
//					Intent intent = new Intent();
//					intent.setClass(getApplicationContext(), EatenTodayActivity.class);
//					startActivity(intent);
//					finish();	
//				break;
//				default:
//					backButton.performClick();
//			}
//			return true;			
//		}
//	    return super.onKeyDown(keyCode, event);
//	}
	

	@Override
	public void onPause(){
		super.onPause();
		SharedPreferences.Editor editor = getPreferences(0).edit();
		editor.putInt(PREFS_MODE, mode);
		editor.putInt(PREFS_CUR_POS, listView.getFirstVisiblePosition());
		editor.commit();
	}
	
	@Override
	public void onResume(){
		super.onResume();
		setMode(getPreferences(0).getInt(PREFS_MODE, SHOW_GROUPS_MODE));
		listView.setSelection(getPreferences(0).getInt(PREFS_CUR_POS, 0));
	}   
 
	
}